<template>
  <a-modal
    :title="title"
    :after-close="reset"
    @ok="submit"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{style: { width: '80px' }}"
    >
      <a-form-item name="name" label="字典名称">
        <a-input v-model:value="form.name" placeholder="请输入" />
      </a-form-item>
      <a-form-item name="type" label="字典类型">
        <a-input v-model:value="form.type" placeholder="请输入" />
      </a-form-item>
      <a-form-item name="code" label="字典码">
        <a-input v-model:value="form.code" placeholder="请输入" />
      </a-form-item>
      <a-form-item name="value" label="字典值">
        <a-input v-model:value="form.value" placeholder="请输入" />
      </a-form-item>
      <a-form-item name="orderNum" label="排序">
        <a-input-number
          v-model:value="form.orderNum"
          placeholder="请输入"
          :min="0"
          :precision="0"
        />
      </a-form-item>
      <a-form-item name="remark" label="备注">
        <a-input v-model:value="form.remark" placeholder="请输入" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { saveDict, getDictById } from './api';
import { Dict, type IDict } from './entity';
import { validReg } from '@/utils/validate';

const props = withDefaults(defineProps<{
  data: Partial<IDict>
}>(),{
})
const title = computed(() => props.data.id ? '编辑' : '新增')
const { formRef, submit, close } = useDialog({ validCallback: save })

let form = $ref(new Dict())
watchEffect(() => {
  if (props.data.id) {
    getDictById(props.data.id).then(dict => {
      form.setProps(dict)
    })
  }
})

const rules = {
  name: [validReg('required', '请输入字典名称')],
  type: [validReg('required', '请输入字典类型')],
  code: [validReg('required', '请输入字典码')],
  value: [validReg('required', '请输入字典值')],
}

onMounted(() => {
})
const emit = defineEmits(['change'])
function save() {
  saveDict(form).then(() => {
    AntMessage.success('保存成功')
    close()
    emit('change')
  })
}

function reset() {
  form = new Dict()
}
</script>

<style lang="less"></style>